﻿//文件指定编译编码UTF-8
#pragma execution_character_set("utf-8")

/**
*    @file:    senserconnect.cpp
*    @brief:
*    @author:  sanshi522@163.com
*    @date:    2025-03-10  17:56
*/
#include "senserconnect.h"
#include <QtCore>
#include <QDebug>


SenserConnect::SenserConnect()
{
    m_run_state = false;
    m_connect_state = false;
    m_adapter_state = false;
    m_connectName = "";
    m_address = "";
    m_port = 0;

    m_senser_client = std::make_shared<SenserClient>();

    openAdapter();
}

SenserConnect::~SenserConnect()
{
    if(m_run_state){
        stop();
    }
    if(m_adapter_state){
        closeAdapter();
    }
    m_senser_client.reset();
}

void SenserConnect::start()
{
    m_run_state = true;
    m_thread = std::make_shared<std::thread>(&SenserConnect::connectProcess, this);
}

void SenserConnect::openAdapter()
{
    Ice::InitializationData init;
    init.properties = Ice::createProperties();
    init.properties->setProperty("Ice.MessageSizeMax", std::to_string(256 * 1024 * 1024));
    m_communicator = Ice::initialize(init);
    m_ice_adapter_ptr = m_communicator->createObjectAdapter("");
    auto object = m_ice_adapter_ptr->add(m_senser_client, Ice::stringToIdentity("Desig_Slice_Client"))->ice_timeout(3000);
    m_client_prx = Ice::uncheckedCast<desig::slice_api::ClientPrx>(object);
    m_adapter_state = true;
}

void SenserConnect::closeAdapter()
{
    m_client_prx.reset();
    m_ice_adapter_ptr->destroy(); // 先销毁适配器
    m_communicator->shutdown();
    m_communicator->destroy();
    m_communicator.reset();
    m_adapter_state = false;
}

void SenserConnect::disConnect()
{
    if(m_run_state){
        stop();
    }
    if(m_adapter_state){
        closeAdapter();
    }
}

void SenserConnect::stop()
{
    if(m_run_state){
        m_run_state = false;
        m_thread->join();
    }
}

void SenserConnect::setConnectParam(QString &connectName, QString &address, int &port)
{
    if((m_connectName == connectName) && (m_address == address) && (m_port == port)) return;
    m_connectName = connectName;
    m_address = address;
    m_port = port;
    if(m_run_state){
        stop();
    }
    if(m_adapter_state){
        closeAdapter();
    }
    openAdapter();
    start();
}

void SenserConnect::connectProcess()
{
    while(m_run_state){
        if (m_adapter_state && !m_connect_state)
        {
            qDebug() << "尝试连接。。。";
            try
            {
                auto str = QString("%1: default -h %2 -p %3").arg(m_connectName).arg(m_address).arg(m_port).toStdString();
                auto base = m_communicator->stringToProxy(str)->ice_timeout(3000);
                m_server_prx = Ice::checkedCast<desig::slice_api::ServerPrx>(base);
                m_server_prx->ice_getConnection()->setAdapter(m_ice_adapter_ptr);
                m_server_prx->ice_getConnection()->setCloseCallback([this](const ::std::shared_ptr<Ice::Connection>& con)
                {
                    iceConnectError("ICE断开连接");
                });
                m_server_prx->ConnectAsync(m_client_prx);
                iceConnectSuccess();
            }
            catch (const std::exception& ex)
            {
                iceConnectError(ex.what());
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
        }
        else
        {
            try
            {
                m_server_prx->ice_getConnection()->heartbeat();
            }
            catch (const std::exception& ex)
            {
                iceConnectError(ex.what());
            }
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }
}

void SenserConnect::iceConnectSuccess()
{
    m_connect_state = true;
    qDebug() << "连接成功";
}

void SenserConnect::iceConnectError(const string message)
{
    m_connect_state = false;
    qDebug() << "连接断开" << message.c_str();

}
